<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      table {
        width: 500px;
        text-align: center;
        border-collapse: collapse;
      }
      th,
      td {
        border: 1px solid purple;
      }
    </style>
  </head>

  <body>
    <table>
      <thead>
        <tr>
          <th>订单编号</th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>

        </tr>
      </thead>
      <tbody>
        <!-- <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
          <td>5</td>
        </tr> -->
      </tbody>
    </table>
    <div class="total">
      <div>合计：<span class="amount">1000.00</span></div>
    </div>
  </body>
  <script>
    // 2、将以下数据使用 forEach 遍历渲染到表格中（自己实现表格），并使用 reduce 方法计算出商品列表里面的总价
    const items = [
      { id: 1, name: '小米13pro', price: 39, quantity: 2 },
      { id: 2, name: '卫龙大面筋', price: 59, quantity: 10 },
      {
        id: 3,
        name:'卫龙',
        price: 120.9,
        quantity: 1,
      },
      { id: 4, name: 'MacBook Pro M2芯片', price: 20, quantity: 1 },
    ]
    function ShoppingCart(items){
      this.items=items
    }
  const cart=new ShoppingCart(items)
  // 统计求和
  ShoppingCart.prototype.totalPrice=function(){
    return this.items.reduce((sum,item)=>{
      return sum+((item.price*item.quantity*10)/10)
    },0).toFixed(2)
  }  // 增
  ShoppingCart.prototype.addItem=function(obj){
    this.items.push(obj)
    return this.items
      
  }


  // 删
  // console.log(cart);
  ShoppingCart.prototype.removeItem=function(id){
    const index=this.items.findIndex(item=>{
        return item.id===id
    })
    this.items.splice(index,1)
    return this

  }
  ShoppingCart.prototype.updateItem=function(id,quantity){
    this.items.forEach (item=>{
           if(item.id===id){
            item.quantity=quantity
          }
         return this
    })
  }


    // 增
  cart.addItem({ id: 5, name: 'MacBook Pro M2芯片', price: 20000, quantity: 1 })
    // 增
  cart.addItem({ id: 6, name: 'MacBook Pro M2芯片', price: 20000, quantity: 1 })
  // 删
  cart.removeItem(4)
  // 更新
  cart.updateItem(5,7)
    // 求和
 
  const tbody= document.querySelector('tbody');
  const amount= document.querySelector('.amount');
    function render(arr){
      tbody.innerHTML= arr.items.map(item=>{
        return `<tr>
          <td>${item.id}</td>
          <td>${item.name}</td>
          <td>${item.price}</td>
          <td>${item.quantity}</td>
        </tr>`
      }).join('')

    }
  render(cart)
  amount.innerHTML=`${ cart.totalPrice()}`
  

  
 



  </script>
</html>
